import { request, tools, base64 } from 'utils'

const ecityTable = {
  /**
   * 功能：调用众智手动维护数据库接口，见：ecity_js_api1.0/frame/task/table.js
   * @param {*} options 
   */
  query(options, tablename) {
    let { data, url, method = 'get' } = options

    // 处理URL,有tablename时，拼接方式如下
    if(tablename) url = `${url}/table/${tablename}/query`;

    url = `${url}?f=json&_t=${new Date().getMilliseconds()}`;

    // 枚举参数进行处理
    if (Array.isArray(data.outFields)) data.outFields = data.outFields.toString();
    if (Array.isArray(data.orderByFields)) data.orderByFields = data.orderByFields.toString();
    if (Array.isArray(data.groupByFieldsForStatistics)) data.groupByFieldsForStatistics = data.groupByFieldsForStatistics.toString();
    if (Array.isArray(data.outStatistics)) data.outStatistics = JSON.stringify(data.outStatistics);
    if (Object.prototype.toString.call(data.returnDistinctValues) === "[object Object]") data.returnDistinctValues = JSON.stringify(data.returnDistinctValues);
    if (Array.isArray(data.objectIds)) data.objectIds = data.objectIds.join(',');

    // 见：ecity_js_api1.0/frame/task/table.js
    // 对 where 进行base64判断，如果没有编码进行base64编码
    var checkWhere = data.where;
    if (typeof checkWhere === 'string') {
      if (!base64.isBase64URL(checkWhere)) {
        data.where = base64.encodeURL(checkWhere);
      }
    }

    let ajaxOption = {
      url,
      method
    }
    if (JSON.stringify(data).length > 1024) {
      ajaxOption.method = 'POST';
      ajaxOption.data = data
    } else {
      data = tools.objectToQueryString(data)
      ajaxOption.url = `${url}&${data}`
    }
    return request(ajaxOption)
  }
}

export default ecityTable;